/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.BusinessProcess;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.ProcessStructure;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class BusinessProcessJpaController implements Serializable {

    public BusinessProcessJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public BusinessProcessJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(BusinessProcess businessProcess) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (businessProcess.getProcessStructureCollection() == null) {
            businessProcess.setProcessStructureCollection(new ArrayList<ProcessStructure>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = businessProcess.getComponent();
        if (componentOrphanCheck != null) {
            BusinessProcess oldBusinessProcessOfComponent = componentOrphanCheck.getBusinessProcess();
            if (oldBusinessProcessOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type BusinessProcess whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Component component = businessProcess.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                businessProcess.setComponent(component);
            }
            Collection<ProcessStructure> attachedProcessStructureCollection = new ArrayList<ProcessStructure>();
            for (ProcessStructure processStructureCollectionProcessStructureToAttach : businessProcess.getProcessStructureCollection()) {
                processStructureCollectionProcessStructureToAttach = em.getReference(processStructureCollectionProcessStructureToAttach.getClass(), processStructureCollectionProcessStructureToAttach.getProcessStructurePK());
                attachedProcessStructureCollection.add(processStructureCollectionProcessStructureToAttach);
            }
            businessProcess.setProcessStructureCollection(attachedProcessStructureCollection);
            em.persist(businessProcess);
            if (component != null) {
                component.setBusinessProcess(businessProcess);
                component = em.merge(component);
            }
            for (ProcessStructure processStructureCollectionProcessStructure : businessProcess.getProcessStructureCollection()) {
                BusinessProcess oldBusinessProcessOfProcessStructureCollectionProcessStructure = processStructureCollectionProcessStructure.getBusinessProcess();
                processStructureCollectionProcessStructure.setBusinessProcess(businessProcess);
                processStructureCollectionProcessStructure = em.merge(processStructureCollectionProcessStructure);
                if (oldBusinessProcessOfProcessStructureCollectionProcessStructure != null) {
                    oldBusinessProcessOfProcessStructureCollectionProcessStructure.getProcessStructureCollection().remove(processStructureCollectionProcessStructure);
                    oldBusinessProcessOfProcessStructureCollectionProcessStructure = em.merge(oldBusinessProcessOfProcessStructureCollectionProcessStructure);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findBusinessProcess(businessProcess.getId()) != null) {
                throw new PreexistingEntityException("BusinessProcess " + businessProcess + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(BusinessProcess businessProcess) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            BusinessProcess persistentBusinessProcess = em.find(BusinessProcess.class, businessProcess.getId());
            Component componentOld = persistentBusinessProcess.getComponent();
            Component componentNew = businessProcess.getComponent();
            Collection<ProcessStructure> processStructureCollectionOld = persistentBusinessProcess.getProcessStructureCollection();
            Collection<ProcessStructure> processStructureCollectionNew = businessProcess.getProcessStructureCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                BusinessProcess oldBusinessProcessOfComponent = componentNew.getBusinessProcess();
                if (oldBusinessProcessOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type BusinessProcess whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            for (ProcessStructure processStructureCollectionOldProcessStructure : processStructureCollectionOld) {
                if (!processStructureCollectionNew.contains(processStructureCollectionOldProcessStructure)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain ProcessStructure " + processStructureCollectionOldProcessStructure + " since its businessProcess field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                businessProcess.setComponent(componentNew);
            }
            Collection<ProcessStructure> attachedProcessStructureCollectionNew = new ArrayList<ProcessStructure>();
            for (ProcessStructure processStructureCollectionNewProcessStructureToAttach : processStructureCollectionNew) {
                processStructureCollectionNewProcessStructureToAttach = em.getReference(processStructureCollectionNewProcessStructureToAttach.getClass(), processStructureCollectionNewProcessStructureToAttach.getProcessStructurePK());
                attachedProcessStructureCollectionNew.add(processStructureCollectionNewProcessStructureToAttach);
            }
            processStructureCollectionNew = attachedProcessStructureCollectionNew;
            businessProcess.setProcessStructureCollection(processStructureCollectionNew);
            businessProcess = em.merge(businessProcess);
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setBusinessProcess(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setBusinessProcess(businessProcess);
                componentNew = em.merge(componentNew);
            }
            for (ProcessStructure processStructureCollectionNewProcessStructure : processStructureCollectionNew) {
                if (!processStructureCollectionOld.contains(processStructureCollectionNewProcessStructure)) {
                    BusinessProcess oldBusinessProcessOfProcessStructureCollectionNewProcessStructure = processStructureCollectionNewProcessStructure.getBusinessProcess();
                    processStructureCollectionNewProcessStructure.setBusinessProcess(businessProcess);
                    processStructureCollectionNewProcessStructure = em.merge(processStructureCollectionNewProcessStructure);
                    if (oldBusinessProcessOfProcessStructureCollectionNewProcessStructure != null && !oldBusinessProcessOfProcessStructureCollectionNewProcessStructure.equals(businessProcess)) {
                        oldBusinessProcessOfProcessStructureCollectionNewProcessStructure.getProcessStructureCollection().remove(processStructureCollectionNewProcessStructure);
                        oldBusinessProcessOfProcessStructureCollectionNewProcessStructure = em.merge(oldBusinessProcessOfProcessStructureCollectionNewProcessStructure);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = businessProcess.getId();
                if (findBusinessProcess(id) == null) {
                    throw new NonexistentEntityException("The businessProcess with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            BusinessProcess businessProcess;
            try {
                businessProcess = em.getReference(BusinessProcess.class, id);
                businessProcess.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The businessProcess with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<ProcessStructure> processStructureCollectionOrphanCheck = businessProcess.getProcessStructureCollection();
            for (ProcessStructure processStructureCollectionOrphanCheckProcessStructure : processStructureCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This BusinessProcess (" + businessProcess + ") cannot be destroyed since the ProcessStructure " + processStructureCollectionOrphanCheckProcessStructure + " in its processStructureCollection field has a non-nullable businessProcess field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Component component = businessProcess.getComponent();
            if (component != null) {
                component.setBusinessProcess(null);
                component = em.merge(component);
            }
            em.remove(businessProcess);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<BusinessProcess> findBusinessProcessEntities() {
        return findBusinessProcessEntities(true, -1, -1);
    }

    public List<BusinessProcess> findBusinessProcessEntities(int maxResults, int firstResult) {
        return findBusinessProcessEntities(false, maxResults, firstResult);
    }

    private List<BusinessProcess> findBusinessProcessEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(BusinessProcess.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public BusinessProcess findBusinessProcess(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(BusinessProcess.class, id);
        } finally {
            em.close();
        }
    }

    public int getBusinessProcessCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<BusinessProcess> rt = cq.from(BusinessProcess.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
